<?php
ob_start();
session_start();
include "checksession.php";
date_default_timezone_set('Asia/Bangkok');
include("../connect.php");
$addFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
    $addFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
?>
<html>
    <head>
        <title>Adinop Co., Ltd. was founded as an ingredients importer and local manufacturers’ distributor in 1986. We also function as an exporter of finished products</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script type="text/javascript" src="../js/jquery/jquery-latest.min.js"></script>
        <link type="text/css" href="../css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
        <script src="../js/jquery/jquery-1.4.3.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="../js/jquery/jquery-ui-1.7.2.custom.min.js"></script>
        <script type="text/javascript" src="../js/jquery/timepicker.js"></script>
        <link rel="stylesheet" href="../css/style.css"/>
    </head>
    <script type="text/javascript">
        $(function() {
            $('#datetime').datepicker({
                duration: '',
                dateFormat: "yy-mm-dd",
                constrainInput: false
            });
            $('#stDateTime').datepicker({
                duration: '',
                dateFormat: "yy-mm-dd",
                constrainInput: false
            });
                 $('#enDateTime').datepicker({
                duration: '',
                dateFormat: "yy-mm-dd",
                constrainInput: false
            });
        });
    </script>

    <script type="text/javascript">
        function KeyCodeInt(objId)
        {
            if (event.keyCode >= 48 && event.keyCode <= 57) //48-57(ตัวเลข) ,65-90(Eng ตัวพิมพ์ใหญ่ ) ,97-122(Eng ตัวพิมพ์เล็ก)
            {
                return true;
            }
            else
            {
                alert("กรอกได้เฉพาะตัวเลข 0-9 เท่านั้นครับ");
                event.returnValue = false;
            }
        }

        function KeyCodeEng(objId)
        {
            if (event.keyCode >= 97 && event.keyCode <= 122) //48-57(ตัวเลข) ,65-90(Eng ตัวพิมพ์ใหญ่ ) ,97-122(Eng ตัวพิมพ์เล็ก)
            {
                return true;
            }
            else
            {
                alert("กรอกได้เฉพาะตัวพิมพ์เล็ก a-z");
                event.returnValue = false;
            }
        }

        function CheckThai(sText, obj) {
            var ValidChars = "กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬหอฮ ะา ิ ี ึ ื ุ ูฤๅฦ ์ ำ ๋ ๊ ็ ่ ้ ั โไใ เ แ '; ";
            var IsNumber = true;
            var Char;
            for (i = 0; i < sText.length && IsNumber == true; i++) {
                Char = sText.charAt(i);
                if (ValidChars.indexOf(Char) == -1) {
                    IsNumber = false;
                }
            }
            if (IsNumber == false) {
                alert("กรอกได้เฉพาะภาษาไทย");
                obj.value = "";
            }
        }
    </script>
    <script language="javascript">
        function CheckValidate()
        {
            if (eval("document.frmMain.txtName_eng.value") == "") {
                alert("กรุณากรอกช่อง Name(ENG)");
                eval("document.frmMain.txtName_eng.focus();")
                return false;
            }

            if (eval("document.frmMain.txtSurname_eng.value") == "") {
                alert("กรุณากรอกช่อง Surname(ENG)");
                eval("document.frmMain.txtSurname_eng.focus();")
                return false;
            }

            if (eval("document.frmMain.txtDepartment.value") == "") {
                alert("กรุณาเลือกช่อง Department");
                eval("document.frmMain.txtDepartment.focus();")
                return false;
            }

            if (eval("document.frmMain.txtName_th.value") == "") {
                alert("กรุณากรอกช่อง Name(TH)");
                eval("document.frmMain.txtName_th.focus();")
                return false;
            }

            if (eval("document.frmMain.txtSurname_th.value") == "") {
                alert("กรุณากรอกช่อง Surname(TH)");
                eval("document.frmMain.txtSurname_th.focus();")
                return false;
            }

            if (eval("document.frmMain.txtUsername.value") == "") {
                alert("กรุณากรอกช่อง Username");
                eval("document.frmMain.txtUsername.focus();")
                return false;
            }

            if (eval("document.frmMain.txtadmaillocal.value") == "") {
                alert("กรุณากรอกช่อง admail.local");
                eval("document.frmMain.txtadmaillocal.focus();")
                return false;
            }
            /*
             if(eval("document.frmMain.txtadinopcoth.value")==""){
             alert("กรุณากรอกช่อง adinop.co.th");
             eval("document.frmMain.txtadinopcoth.focus();")
             return false;
             }
             */
            if (document.frmMain.chkreq.checked == false) {
                alert("กรุณาติ๊กช่อง I agree");
                document.frmMain.chkreq.focus();
                return false;
            }

            if (document.frmMain.txtName_eng.value != document.frmMain.txtUsername.value) {
                alert("กรุณากรอกชื่อให้เหมือนกัน");
                document.frmMain.txtUsername.focus();
                return false;
            }

            if (document.frmMain.txtEmployee_id.value.length < 8) {
                alert('กรุณากรอกตัวเลข 8 ตัว');
                return false;
            }
        }
    </script>
    <script type="text/javascript">
        $(document).ready(function() {

            $("#txtEmployee_id").change(function() {

                $("#txtEmployee_id").empty();

                $.ajax({
                    url: "returnEmployee.php",
                    type: "POST",
                    data: 'sCusID=' + $("#txtEmployee_id").val()
                })
                        .success(function(result) {

                    var obj = jQuery.parseJSON(result);

                    if (obj == '')
                    {
                        $("#txtName_eng").val('');
                        $("#txtSurname_eng").val('');
                        $("#txtName_th").val('');
                        $("#txtSurname_th").val('');
                        $("#txtUsername").val('');
                        $("#txtadmaillocal").val('');
                        $("#txtadinopcoth").val('');
                    }
                    else
                    {
                        $.each(obj, function(key, inval) {

                            if ($("#txtEmployee_id").val() == inval["id_member"]) {

                                $("#txtEmployee_id").val(inval["id_member"]);
                                $("#txtName_eng").val(inval["f_name_e"]);
                                $("#txtSurname_eng").val(inval["l_name_e"]);
                                $("#txtName_th").val(inval["f_name"]);
                                $("#txtSurname_th").val(inval["l_name"]);
                                $("#txtStartdate").val(inval["date_inwork"]);
                                $("#txtUsername").val(inval["f_name_e"]);
                                $("#txtadmaillocal").val(inval["i_email"]);
                                $("#txtadinopcoth").val(inval["x_email"]);
                            } else {
                                $("#txtEmployee_id").val(inval["emp_id"]);
                                $("#txtName_eng").val(inval["emp_nameEng"]);
                                $("#txtSurname_eng").val(inval["emp_surnameEng"]);
                                $("#txtName_th").val(inval["emp_nameTh"]);
                                $("#txtSurname_th").val(inval["emp_surnameTh"]);
                                $("#txtStartdate").val(inval["emp_startDate"]);
                                $("#txtUsername").val(inval["emp_nameEng"]);
                                $("#txtadmaillocal").val(inval["mail_local"]);
                                $("#txtadinopcoth").val(inval["mail_coth"]);
                            }
                            $.each($('select#txtDepartment>option'), function() {
                                if ($(this).val() == inval["de_id"]) {
                                    $(this).attr("selected", true);
                                } else {
                                    $(this).attr("selected", false);
                                }
                            });

                        });

                    }

                });

            });
        });
    </script>
    <script type='text/javascript'>
        function check_emaillocal(elm) {
            var regex_email = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*\@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{2,5})$/
            if (!elm.value.match(regex_email)) {
                elm.value = '';
                alert('รูปแบบ email ไม่ถูกต้อง example@admail.local');
            }
        }
    </script>
    <script type='text/javascript'>
        function check_emailcoth(elm) {
            var regex_email = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*\@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.([a-zA-Z]){2,5})$/
            if (!elm.value.match(regex_email)) {
                elm.value = '';
                alert('รูปแบบ email ไม่ถูกต้อง example@adinop.co.th');
            }
        }
    </script>
    <body>
    <body>
    <body class="body">

        <table align="center" width="90%">
            <tr>
                <td colspan="2" class="header" >
                    <img src="../images/logo.png"> เพิ่มรายชื่ออุปกรณ์ 
                    <hr/>
                </td>
            </tr >
        </table>

        <div align="center">
            <fieldset style="width:60%">
                <legend class="nameTitle">รายละเอียด</legend>
                <br>
                <form action="<? $addFormAction; ?>" method="post" name ="frmMain" id="frmMain" ENCTYPE="multipart/form-data" OnSubmit="return CheckValidate();" />
                <table width="700" border="0" class="inputcontenttable">
                    <tr>
                        <th width="40%">
                    <div align="right">ประเภท : </div></th>
                    <th><div align="left">
                        <select name="txttype_id" id="txttype_id" OnChange="window.location = '?item=' + this.value;" >
                            <option value=""><-- เลือกประเภทอุปกรณ์  --></option>
                            <?
                            $strSQL = "SELECT * FROM prd_type ORDER BY type_id ASC";
                            $objQuery = mysql_query($strSQL);
                            mysql_query("SET NAMES UTF8");
                            while ($objResult = mysql_fetch_array($objQuery)) {
                                $objResult["type_name"] = iconv("UTF-8", "ISO-8859-11", $objResult["type_name"]);

                                if ($_GET["item"] == $objResult["type_id"]) {
                                    $sel = "selected";
                                } else {
                                    $sel = "";
                                }
                                ?>
                                <option value="<?= $objResult["type_id"]; ?>" <?= $sel; ?>><?= $objResult["type_name"]; ?></option>
                                <?
                            }
                            ?>
                        </select></div></th>
                    </tr>

                    <tr>
                        <th width="40%">
                    <div align="right">ชื่ออุปกรณ์ : </div></th>
                    <th><div align="left">
                        <input type="text" name="txtprd_name" id="txtprd_name" size="30" placeholder="" />
                        <span id="mySpan1"></span></div></th>
                    </div></th>
                    </tr>

                    <tr>
                        <th width="40%">
                    <div align="right">จำนวนอุปกรณ์ : </div></th>
                    <th><div align="left">
                        <input type="text" name="txtprd_amount" id="txtprd_amount" size="10" placeholder="" />
                    </div></th>
                    </tr>

                    <tr>
                        <th width="40%"> 
                    <div align="right">รูปภาพ : </div></th>
                    <th width="236"><div align="left">
                        <input type="file" name="fileupload" id="fileupload" size="32" />
                    </div></th>
                    </tr>

                    <tr>
                        <th width="40%"> 
                    <div align="right">วันที่ : </div></th>
                    <th width="236"><div align="left">
                        <input type="text" name="datetime" id="datetime" size="20" />
                    </div></th>
                    </tr>
                    
                      <tr>
                        <th width="40%"> 
                    <div align="right">เริ่มประกัน : </div></th>
                    <th width="236"><div align="left">
                        <input type="text" name="stDateTime" id="stDateTime" size="20" />
                    </div></th>
                    </tr>
 <tr>
                        <th width="40%"> 
                    <div align="right">สิ้นสุดประกัน : </div></th>
                    <th width="236"><div align="left">
                        <input type="text" name="enDateTime" id="enDateTime" size="20" />
                    </div></th>
                    </tr>
                    <tr>
                        <th width="40%">
                    <div align="right">หมายเหตุ : </div></th>
                    <th><div align="left">
                        <textarea name="txtprd_remark" rows="4" cols="50" id="txtprd_remark"  wrap="off" placeholder="หมายเหตุ"/></textarea>
                        </tr>
                </table>
                <br/>
            </fieldset>
            <br/>
            <input name="addmanageTreasury" type="submit" id="addmanageTreasury" value="บันทึก"  style="height: 30px; width: 120px"/>
        </form>
    </div>
</body>

<?
/*
  if(isset($_POST['btnRecordadd'])){
  $txtEmployee_id = $_POST['txtEmployee_id'];
  $txtName_eng = $_POST['txtName_eng'];
  $txtSurname_eng = $_POST['txtSurname_eng'];
  $txtStartdate = $_POST['txtStartdate'];
  //	  $txtDepartname = $_POST['txtDepartname'];
  $txtDepartment = $_POST['txtDepartment'];
  $txtName_th = $_POST['txtName_th'];
  $txtSurname_th = $_POST['txtSurname_th'];
  $txtUsername = $_POST['txtUsername'];
  $txtadmaillocal = $_POST['txtadmaillocal'];
  $txtadinopcoth = $_POST['txtadinopcoth'];
  $txtRemark = $_POST['txtRemark'];
  $txtno = $_POST['txtno'];
  $chkreq = $_POST['chkreq'];
  $txtdatetimereq = $_POST['txtdatetimereq'];

  $sessionuserid = $_SESSION["UserID"];

  $sql = "select * from employee where emp_id = '$txtEmployee_id' or emp_nameEng = '$txtName_eng' ";
  $query_id = mysql_query($sql);
  if(mysql_num_rows($query_id) > 0){
  echo "	<script language='javascript'>
  alert('รหัสเจ้าหน้าที่ซ้ำ หรือ ชื่อภาษาอังกฤษซ้ำ');
  </script>";
  exit();
  }

  $sql3 = "select * from employee where emp_no13u = '$txtno' ";
  $query_id3 = mysql_query($sql3);
  if(mysql_num_rows($query_id3) > 0){
  echo "	<script language='javascript'>
  alert('รหัสNO. 13-S ซ้ำ');
  </script>";
  exit();
  }
  ?>
  <?
  $sqldepart = "select departname from depart where de_id = '$txtDepartment' ";
  $query_departname = mysql_query($sqldepart);
  while ($objResult = mysql_fetch_array($query_departname)) {
  $txtDepartname = $objResult['departname'];
  }
  ?>
  <?
  $sql1 = "INSERT INTO employee (emp_id , m_id , emp_nameEng , emp_surnameEng , emp_startDate , emp_department , emp_nameTh , emp_surnameTh , emp_no13u ,emp_createDate , de_id , cn_id) VALUES ('$txtEmployee_id','$sessionuserid','$txtName_eng','$txtSurname_eng','$txtStartdate','$txtDepartname','$txtName_th','$txtSurname_th','$txtno','','$txtDepartment','')";
  $query_id1 = mysql_query($sql1);

  $sql2 = "INSERT INTO  `db_itmanager`.`mail` (`mail_id` ,`emp_id` ,`mail_username` ,`mail_local` ,`mail_coth` ,`mail_remark` ,`mail_request` ,`mail_requestDate` ,`mail_authorized` ,`mail_authorizedDate` ,`mail_requestUser` ,`mail_requestUserDate` ,`mail_staffIT` ,`mail_staffITdate` ,`mail_authorizedCon` ,`mail_authorizedConDate` ,`mail_supervisor` ,`mail_supervisorDate`) VALUES ('',  '$txtEmployee_id',  '$txtUsername', '$txtadmaillocal',  '$txtadinopcoth',  '$txtRemark',  '$chkreq',  SYSDATE(),  '',  '',  '',  '',  '',  '',  '',  '',  '',  '')";
  $query_id2 = mysql_query($sql2);

  if($query_id1){
  echo "<script language='javascript'>
  alert('Complete');
  setTimeout(\"parent.$.fancybox.close()\",1000);
  </script>";
  echo "<meta http-equiv='refresh' content='5; url=recordadd.php'>";
  }
  }
 */

if (isset($_POST['addmanageTreasury'])) {
    $txttype_id = $_POST['txttype_id'];
    $txtprd_name = $_POST['txtprd_name'];
    $txtprd_amount = $_POST['txtprd_amount'];
//	  $txtprd_pic = $_POST['txtprd_pic'];
    $datetime = $_POST['datetime'];
    $stDateTime = $_POST['stDateTime'];
    $enDateTime = $_POST['enDateTime'];
    $txtprd_remark = $_POST['txtprd_remark'];

    $pic = $_FILES['fileupload']['name'];
    $pic = iconv("tis-620", "utf-8", $pic);
    uppic_only($_FILES["fileupload"], "photo/");


    $recMaxOrder = mysql_fetch_array(mysql_query('SELECT MAX(prd_id) FROM product'));
    $numRowsOrder = $recMaxOrder[0] + 1;


    $sql1 = "INSERT INTO product (prd_id , prd_name , prd_amount , prd_balance , prd_pic , type_id , prd_inDate , prd_remark) VALUES ('$numRowsOrder','$txtprd_name','$txtprd_amount','$txtprd_amount','$pic','$txttype_id','$datetime','$txtprd_remark')";
    $query_id1 = mysql_query($sql1);

    for ($i = 1; $i <= $txtprd_amount; $i++) {

        $strSQL5 = "SELECT * FROM product INNER JOIN prd_type ON product.type_id = prd_type.type_id INNER JOIN product_detail ON product.prd_id = product_detail.prd_id WHERE product.type_id = '" . $txttype_id . "' ORDER BY product_detail.pd_code DESC";

        $objQuery5 = mysql_query($strSQL5);
        $objResult5 = mysql_fetch_array($objQuery5);
        $rsproduct_code = $objResult5["pd_code"];

        if ($rsproduct_code != "") {
            $rsproduct_code = explode(".", $rsproduct_code);
            $rs = $rsproduct_code[0] . $rsproduct_code[1];
            $num = $rs + 1;
            $rsproduct_code = preg_replace('|^(\d{1})(\d{5})|', '$1.$2', $num);
        }

        if ($rsproduct_code == "") {
            $rsproduct_code = $txttype_id . ".00001";
            echo $rsproduct_code;
        }

        $sql2 = "INSERT INTO  `db_itmanager`.`product_detail` (`pd_id` ,`prd_id` ,`pd_codeAdinop` ,`pd_code` ,`pd_name` ,`emp_id` ,`pd_status` ,`pd_outDate` ,`pd_stWarunty` ,`pd_enWarunty` ,`pd_remark`) VALUES ('',  '$numRowsOrder', '', '$rsproduct_code',  '$txtprd_name',  '',  'NoUse', NULL,  '$stDateTime',  '$enDateTime',  '')";
        $query_id2 = mysql_query($sql2);
    }
    if ($query_id1) {
        echo "<script language='javascript'>
			   alert('Insert Complete');
			   setTimeout(\"parent.$.fancybox.close()\",1000); 
			  </script>";
        echo "<meta http-equiv='refresh' content='1; url=manageTreasury.php'>";
    }
}
?>
<?php

function uppic_only($img, $imglocate, $limit_size = 2000000, $limit_width = 0, $limit_height = 0) {
    $allowed_types = array("jpg", "jpeg", "gif", "png");
//	echo "1<br>";
    if ($img["name"] != "") {
        $fileupload1 = $img["tmp_name"];
        $data_Img = @getimagesize($fileupload1);
        $g_img = explode(".", $img["name"]);
        $ext = strtolower(array_pop($g_img));
        $file_up = $_FILES['fileupload']['name'] . $i_num . "." . $ext;
        $canUpload = 0;
//		echo "2<br>";
        if (isset($data_Img) && $data_Img[0] > 0 && $data_Img[1] > 0) {
//			echo "3<br>";
            if ($img["size"] <= $limit_size) {
                if ($limit_width > 0 && $limit_height > 0) {
                    if ($data_Img[0] <= $limit_width && $data_Img[1] <= $limit_height) {
                        $canUpload = 1;
                        echo "5<br>";
                    }
                } else if ($limit_width > 0 && $limit_height == 0) {
                    if ($data_Img[0] <= $limit_width) {
                        $canUpload = 1;
                        echo "6<br>";
                    }
                } else if ($limit_width == 0 && $limit_height > 0) {
                    if ($data_Img[1] <= $limit_height) {
                        $canUpload = 1;
                        echo "7<br>";
                    }
                } else {
                    $canUpload = 1;
//					echo "8<br>";
                }
            } else {
                echo "<script language='javascript'>
		  $(document).ready(function(){
			apprise('â»Ã´ãÊèä¿ÅìÃÙ»¢¹Ò´äÁèà¡Ô¹ 2 MB', {'animate':true}, function (){
				});
			})
		  </script>";
                exit();
            }
        }
        if ($fileupload1 != "" && @in_array($ext, $allowed_types) && $canUpload == 1) {
            @copy($fileupload1, $imglocate . $file_up);
            @chmod($imglocate . $file_up, 0777);
        } else {
            $file_up = "";
        }
    }
    return $file_up; // Êè§¡ÅÑºª×èÍä¿Åì
}
?>
</html>
